﻿using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using Terranova.API;

namespace SMSRulez
{
    public partial class Form1 : Form
    {
        DataTable tableRule;
        HiddenFolderClass hideFolder;
        static string location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
        string PASSWORD = string.Empty;
        int showMessageCount = 1;
        DB db;
        public Form1()
        {
            db = new DB(location);
            InitializeComponent();
        }

        private void bttnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bttnOk_Click(object sender, EventArgs e)
        {
            PASSWORD = textPassword.Text;
            PasswordToKey(PASSWORD);
            if (CheckPassword(PASSWORD))
            {
                smsModeChanged = false;
                ToggleThreadMode();
                Cursor.Current = Cursors.WaitCursor;
                hideFolder.MoveMessagesFromHiddenFolderToPrivateFolder(showMessageCount);
                ToggleThreadMode();
                OpenSMSInbox();
                Cursor.Current = Cursors.Default;
            }
            else
            {
                textPassword.Text = "";
            }

        }
        bool smsModeChanged = false;
        private void ToggleThreadMode()
        {
            //HKEY_CURRENT_USER\Software\Microsoft\Inbox\Settings\OEM\SMSInboxThreadingDisabled
            try
            {
                while (ProcessCE.IsRunning(@"\Windows\tmail.exe"))
                {
                    ProcessCE.FindAndKill(@"\Windows\tmail.exe");
                }
                RegistryKey reg = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("Microsoft").CreateSubKey("Inbox").CreateSubKey("Settings").CreateSubKey("OEM");
                if (!smsModeChanged)
                {
                    bool isThreadDisabled = reg.GetValue("SMSInboxThreadingDisabled", "1").ToString() == "1" ? true : false;
                    if (!isThreadDisabled)
                    {
                        reg.SetValue("SMSInboxThreadingDisabled", "1", RegistryValueKind.DWord);
                        smsModeChanged = true;
                        Process.Start(@"\Windows\tmail.exe", "-Service \"SMS\" -RunInBKG");
                    }
                }
                else
                {
                    reg.SetValue("SMSInboxThreadingDisabled", "0", RegistryValueKind.DWord);
                }
                reg.Flush();
            }
            catch (Exception ex) { string mess = ex.Message; }

        }

        private bool CheckPassword(string password)
        {
            string command = "SELECT * FROM Password WHERE password = '" + password.Trim() + "'"; //Check password from database
            db.SetConnection(command, DB.sqlAction.Select, out tableRule);
            if (tableRule.Rows.Count < 1)
            {
                MessageBox.Show("Wrong Password", "ERROR");
                return false;
            }
            else
            {
                hideFolder = new HiddenFolderClass(password.Trim());
                return true;
            }
        }

        private void OpenSMSInbox()
        {
            Process inbox = new Process();
            inbox.StartInfo.FileName = @"\Windows\tmail.exe";
            inbox.StartInfo.UseShellExecute = true;
            inbox.StartInfo.Arguments = @"-service ""SMS"" ";
            inbox.Start();
            
        }
        
        
        private void PasswordToKey(string password)
        {
            RijndaelManaged sa = new RijndaelManaged();
            HashAlgorithm hashAlgo = new MD5CryptoServiceProvider();
            byte[] hash = hashAlgo.ComputeHash(Encoding.UTF8.GetBytes(password));
            sa.BlockSize = hash.Length * 8;
            sa.Key = hash;
            sa.IV = hash;
            PASSWORD = Encrypt(sa);
        }
        private string Encrypt(SymmetricAlgorithm sa)
        {
           

            ICryptoTransform encryptor = sa.CreateEncryptor(sa.Key, sa.IV);
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] inPass = encoding.GetBytes(PASSWORD);
            MemoryStream outStream = new MemoryStream();
            CryptoStream outPass = new CryptoStream(outStream, encryptor, CryptoStreamMode.Write);
            outPass.Write(inPass, 0, inPass.Length);
            outPass.FlushFinalBlock();
            byte[] cipherTextBytes = outStream.ToArray();
            outStream.Close();
            outPass.Close();
            string cipherText = null;
            return cipherText = Convert.ToBase64String(cipherTextBytes);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            showMessageCount = 1;
        }

        private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            HiddenFolderClass hf = new HiddenFolderClass();
            Cursor.Current = Cursors.WaitCursor;
            hf.HideMessageFromPrivateFolder();
            Cursor.Current = Cursors.Default;
            this.Dispose(true);
        }

        private void trackBar1_ValueChanged(object sender, EventArgs e)
        {
            showMessageCount = trackBar1.Value;
            if (showMessageCount != 10)
            {
                showMessageCount = showMessageCount * 10;
                bttnOk.Text = "Show " + showMessageCount.ToString();
                if (showMessageCount == 0)
                {
                    bttnOk.Text = "Show";
                }
                
            }
            else
            {
                showMessageCount = int.MaxValue;
                bttnOk.Text = "Show All";
            }
            bttnOk.Refresh();
        }

    }
}